package com.sanpu.kxe.rxservice;

import android.text.TextUtils;

import com.sanpu.kxe.business.login.bean.LoginOutput;
import com.sanpu.kxe.business.main.view.MainActivity;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.jump.eventbus.OfflineEvent;
import com.sanpu.kxe.utils.AppContextUtil;
import com.sanpu.kxe.utils.SignUtil;
import com.sanpu.kxe.utils.TimeManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description：请求报文
 * Created by 薛勇军 on 2018/6/27.
 */

public class RequestMap {

    private ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

    public RequestMap() {
    }

    public RequestMap(ConcurrentHashMap<String, String> map) {
        this.map = map;
    }

    /**
     * 封装请求参数map
     *
     * @param attachParam
     * @return
     */
    public Map<String, String> getReqParams(boolean attachParam) {
        String key = DataUtils.publicKey;
        if (attachParam) {
            LoginOutput loginOutput = CacheManage.getInstance().getCache(CacheModel.LOGIN_KEY);
            if (loginOutput != null) {
                String sessionId = loginOutput.getSessionId();
                map.put(CommonConfig.SESSIONID, sessionId);
                key = loginOutput.getPrivateKey();
            } else {
                EventBus.getDefault().post(new OfflineEvent("登录信息已失效，请重新登录"));
                AppContextUtil.finishAllExclByActivity(MainActivity.class.getName());
            }
        }
        String timestamp = String.valueOf(TimeManager.getInstance().getCurTimeMillis());
        map.put(CommonConfig.CHARSET, "UTF-8");
        if (!map.containsKey(CommonConfig.VERSION)) {
            map.put(CommonConfig.VERSION, "1.0.0");
        }
        map.put(CommonConfig.SIGNTYPE, "01");
        map.put(CommonConfig.ENCTYPE, "01");
        map.put(CommonConfig.PUBKEYVERSION, "1.0.0");
        map.put(CommonConfig.REQTIME, timestamp);
        map.put(CommonConfig.KEY, key);
        String signStr = SignUtil.getSHA256Str(mapReqStr());
        map.put(CommonConfig.SIGN, signStr);
        if (map.containsKey(CommonConfig.REQDATA)) {
            String reqData = DataUtils.dataEncode(key, map.get(CommonConfig.REQDATA));
            map.put(CommonConfig.REQDATA, reqData);
        }
        //key参与签名，不上传
        map.remove(CommonConfig.KEY);
        return map;
    }

    public String mapReqStr() {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> keys = map.keySet().iterator();
        List<String> keyList = new ArrayList<>();
        while (keys.hasNext()) {
            keyList.add(keys.next());
        }
        //对key进行升序排序
        Collections.sort(keyList);
        for (String key: keyList) {
            if (TextUtils.equals(CommonConfig.KEY, key)) {
                continue;
            }
            String value = map.get(key);
            if (!TextUtils.isEmpty(value)) {
                buffer.append("&" + key + "=" + value);
            }
        }
        //密钥key不参与排序，拼接最后面
        buffer.append("&key=" + map.get(CommonConfig.KEY));
        buffer.delete(0, 1);
        return buffer.toString();
    }

    /**
     * 用于调用H5链接拼接参数
     * @return
     */
    public String map2ReqStr() {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> keys = getReqParams(true).keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = map.get(key);
            buffer.append("&" + key + "=" + value);
        }
        buffer.delete(0, 1);
        return buffer.toString();
    }

    /**
     * 图片访问需拼接sessionId
     */
    public static String sessionIdReqStr() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("?");
        buffer.append(CommonConfig.SESSIONID);
        buffer.append("=");
        LoginOutput loginOutput = CacheManage.getInstance().getCache(CacheModel.LOGIN_KEY);
        if (loginOutput != null) {
            String sessionId = loginOutput.getSessionId();
            buffer.append(sessionId);
        }
        return buffer.toString();
    }

    /**
     * @param key
     * @param value
     */
    public RequestMap put(String key, String value) {
        if (key != null && value != null) {
            map.put(key, value);
        }
        return this;
    }
}
